package com.gy.mbaselibrary.fragment;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;


/**
 * 创建者：高业
 * 邮箱：15234150168@163.com
 * 时间：2018/2/6
 * 描述：
 * 修改人：
 * 修改时间：2018/2/6
 * 修改备注：
 */
public class FragmentFactory {
    private static Map<String, Fragment> mFragments = new HashMap<>();

    public static Fragment createFragment(String tag,Class clz, Bundle bundle) {
        Fragment fragment;
        fragment = mFragments.get(tag);
        if (fragment == null) {
            try {
                //*可以使用相对路径，同一个包中可以不用带包路径*//*
                Constructor c0 = clz.getDeclaredConstructor();
                c0.setAccessible(true);
                fragment = (Fragment)c0.newInstance();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            if (fragment != null) {
                mFragments.put(tag, fragment);
            }
        }
        if (bundle != null)
            fragment.setArguments(bundle);
        return fragment;
    }
    public static Fragment createFragment(String tag,Class clz) {
        return createFragment(tag,clz,null);
    }

    public static Fragment createFragment(Class clz, Bundle bundle) {
        return createFragment(clz.getName(),clz,bundle);
    }
    public static Fragment createFragment(Class clz) {
        return createFragment(clz,null);
    }

    public static void cleanFragment(String tag) {
        if (mFragments != null && mFragments.containsKey(tag)) {
            mFragments.remove(tag);
        }
    }

    public static Fragment getFragment(String tag){
        if (mFragments != null && mFragments.containsKey(tag)){
            return mFragments.get(tag);
        }
        return null;
    }

    public static void cleanFragment(String... tags){
        for (String tag : tags){
            cleanFragment(tag);
        }
    }

    public static void cleanFragment(){
        mFragments.clear();
    }
}
